package com.kady.controller.admin;

import com.alibaba.fastjson.JSON;
import com.kady.entity.ResultVO;
import com.kady.entity.User;
import com.kady.service.AdminService;
import com.kady.service.impl.AdminServiceImpl;
import com.kady.utils.MD5Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Date;
import java.sql.SQLException;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: kady
 * \* Date: 2021/3/23
 * \* Time: 17:15
 * \* 千峰JAVA2101班
 * \* Description: 登录控制
 * \
 */

@WebServlet("/userService/register")
public class AdminRegisterController extends HttpServlet {
    /**
     * 注册接口,不走BaseServlet
     */

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String nickName = req.getParameter("nickName");
        byte gender = Byte.valueOf(req.getParameter("gender"));
        String phone = req.getParameter("phone");
        String email = req.getParameter("email");
        Date user_create_time = new Date(new java.util.Date().getTime());
        byte isVip = Byte.valueOf(req.getParameter("isVip"));
        byte isAdmin = Byte.valueOf(req.getParameter("isAdmin"));
        User newUser = new User(username, MD5Util.md5(password),nickName,gender,phone,email,user_create_time,isVip,isAdmin);
        AdminService adminService = new AdminServiceImpl();
        try {
            ResultVO resultVO = adminService.register(newUser);
            if(resultVO.isSuccess()){
//                req.getRequestDispatcher( "/login.jsp").forward(req,resp);
                resp.sendRedirect(req.getContextPath() + "/login.jsp");
            }else{
                resp.getWriter().write("<script>alert('" + (resultVO).getMessage() +"');window.history.go(-1);</script>");
            }
//            resp.getWriter().write(JSON.toJSONString(resultVO));
        } catch (SQLException | IOException throwables) {
            throwables.printStackTrace();
        }

    }
}
